package org.go.scheduler;

import java.util.Collection;
import java.util.HashMap;

import org.go.expcetion.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * Holds references to Scheduler instances - ensuring uniqueness, and
 * preventing garbage collection, and allowing 'global' lookups - all within a
 * ClassLoader space.
 * </p>
 * 
 * @author HeJie
 */
public class SchedulerRepository {

	private static SchedulerRepository inst;
	private static final Logger log = LoggerFactory.getLogger(SchedulerRepository.class);

	public static synchronized SchedulerRepository getInstance() {
		if (inst == null) {
			inst = new SchedulerRepository();
		}
		return inst;
	}

	private HashMap<String, Scheduler> schedulers;

	private SchedulerRepository() {
		schedulers = new HashMap<String, Scheduler>();
	}

	public synchronized void bind(Scheduler sched) throws SchedulerException {
		if (schedulers.get(sched.getSchedulerName()) != null) {
			throw new SchedulerException("Scheduler with name '" + sched.getSchedulerName() + "' already exists.");
		}
		log.debug("Scheduler with name : {}", sched.getSchedulerName());
		schedulers.put(sched.getSchedulerName(), sched);
	}

	public synchronized Scheduler lookup(String schedName) {
		return schedulers.get(schedName);
	}

	public synchronized Collection<Scheduler> lookupAll() {
		return java.util.Collections.unmodifiableCollection(schedulers.values());
	}

	public synchronized boolean remove(String schedName) {
		return (schedulers.remove(schedName) != null);
	}

}